package com.lavegue.webaction;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.FileUtils;

import com.lavegue.common.BaseAction;
import com.lavegue.common.Constants;
import com.lavegue.model.BisGroup;
import com.lavegue.model.BisType;
import com.lavegue.model.ManageMsg;
import com.lavegue.model.ManageMsgDetail;
import com.lavegue.service.BisGroupService;
import com.lavegue.service.BisTypeService;
import com.lavegue.service.ManageMsgService;
import com.lavegue.util.FileCharsetDetector;
import com.lavegue.util.StringUtil;

/**
 * author: luoweibin
 * date:2011-12-24
 * description:
 *
 */
public class MobanEditAction extends BaseAction {
	private static final String TMP_MSG_DETAIL_KEY = "tmpEditMsgDetail";
	private static final String MSG_KEY = "editMsg";
	private static final int MSG_DETAIL_TOTAL = 5;
	private long msgCapacity = 0;
	private int first;
	private String title;
	private int oldZhenNo = 0;
	private ManageMsgDetail curMsgDetail;
	//第一帧时间间隔
	private int interval1;
	
	//第一帧图片
	private File pic1;
	private String pic1ContentType;
	
	//第一帧音乐
	private File music1;
	private String music1ContentType;
	
	//第一帧手动编辑文字
	private String txtedit1;
	
	//第一帧内容上传的文件
	private File txt1;
	private String txt1ContentType;
	
	private int bisType;
	private int bisGroup;
	private int label;
	private String editTxtContent;
	//标识第几帧
	private int zhenNumber = 1;
	
	private List<BisType> allTypes;
	private List<BisGroup> groups;
	private BisGroupService bisGroupService;
	private BisTypeService bisTypeService;
	private ManageMsgService manageMsgService;
	private List<ManageMsgDetail> yulanList;
	private int msgId;
	public String mobanList() {
		return "list";
	}
	
	public String editMoban() {
		clearSessionContent();
		ManageMsg msg = manageMsgService.findById(msgId);
		this.setSessionAtrribute(MSG_KEY, msg);
		for (ManageMsgDetail md : msg.getManageMsgDetails()) {
			saveMsgDetail(md);
		}
		//让他显示第一帧
		this.curMsgDetail = this.getSessionMsgDetail(1);
		initDate();
		return "editMsg";
	}
	
	private void initDate() {
		allTypes = bisTypeService.findAll();
		//如果是0，表示第一次进入这个页面，如果不是，那应该是发生了错误，再次返回到那个页面
		if (allTypes != null && !allTypes.isEmpty()) {
			List<BisGroup> gs = bisTypeService.findById(this.getSessionMsg().getBisType().getId()).getBisGroups();
			groups = Arrays.asList(gs.toArray(new BisGroup[allTypes.get(0).getBisGroups().size()]));
		}
		
		yulanList = new ArrayList<ManageMsgDetail>();
		for (int i = 0; i < MSG_DETAIL_TOTAL; i++) {
			this.yulanList.add(this.getSessionMsgDetail(i + 1));
		}
		this.reComputeCapacity();
	}
	
	
	/**
	 * 清除本帧
	 * @return
	 */
	public String cleanCurZhen() {
		ManageMsgDetail detail = this.getSessionMsgDetail(this.zhenNumber);
		if (!StringUtil.isEmpty(detail.getPic())) {
			new File(this.getProjectPath()+ detail.getPic()).delete();
		}
		if (!StringUtil.isEmpty(detail.getMusic())) {
			new File(this.getProjectPath()+ detail.getMusic()).delete();
		}
		this.removeSession(TMP_MSG_DETAIL_KEY + this.zhenNumber);
		this.curMsgDetail = null;
		this.addActionMessage("清除成功");
		initDate();
		return "editMsg";
	}
	
	/**
	 * 清除图片
	 * @return
	 */
	public String cleanPic() {
		ManageMsgDetail detail = this.getSessionMsgDetail(this.zhenNumber);
		if (detail.getPic() != null) {
			//new File(this.getProjectPath() + detail.getPic()).delete(); 不删除，删除了发出去的信息记录里面就看不到
			detail.setPic(null);
			this.saveMsgDetail(detail);
		}
		this.addActionMessage("清除彩信图片成功");
		initDate();
		return "editMsg";
	}
	
	public String cleanTxt() {
		ManageMsgDetail detail = this.getSessionMsgDetail(this.zhenNumber);
		detail.setTxt(null);
		this.saveMsgDetail(detail);
		this.addActionMessage("清除彩信文字成功");
		initDate();
		return "editMsg";
	}
	
	public String cleanMusic() {
		ManageMsgDetail detail = this.getSessionMsgDetail(this.zhenNumber);
		if (detail.getMusic() != null) {
			//new File(this.getProjectPath() + detail.getMusic()).delete(); 不删除，删除了发出去的信息记录里面就看不到
			detail.setMusic(null);
			this.saveMsgDetail(detail);
		}
		this.addActionMessage("清除彩信音乐成功");
		initDate();
		return "editMsg";
	}
	
	/**
	 * 跳帧
	 * @return
	 */
	public String changeZhen() {
		this.curMsgDetail = this.getSessionMsgDetail(this.zhenNumber);
		ManageMsgDetail oldZhen = this.getSessionMsgDetail(oldZhenNo);
		oldZhen.setInterval(interval1);
		this.setSessionAtrribute(TMP_MSG_DETAIL_KEY + this.oldZhenNo, oldZhen);
		initDate();
		return "editMsg";
	}
	
	
	public String editTxt()  throws Exception {
		//检查大小
		if (this.editTxtContent.getBytes().length > getRemainCapacity()) {
			this.addActionError("修改失败, 文字过多，超多了整条彩信的最大限制");
			initDate();
			return "editMsg";
		}
		ManageMsgDetail msgDetail = this.getSessionMsgDetail(this.zhenNumber);
		msgDetail.setTxt(this.editTxtContent.trim());
		msgDetail.setInterval(interval1);
		this.saveMsgDetail(msgDetail);
		this.addActionMessage("修改彩信文字成功");
		initDate();
		return "editMsg";
	}
	
	/**
	 * 上传图片
	 * @return
	 * @throws Exception 
	 */
	public String uploadPic() throws Exception {
		System.out.println("uploadPic...........");
		if (pic1 != null) {
			//检查类型
//			if (!this.pic1ContentType.equals("image/jpeg") && !this.pic1ContentType.equals("image/jpg") && !this.pic1ContentType.equals("image/gif")) {
			if(!this.pic1ContentType.toLowerCase().startsWith("image")) {
				this.addActionError("上传失败,彩信图片的格式有误,请重新上传");
				initDate();
				return "editMsg";
			}
			//检查大小
			if (pic1.length() > getRemainCapacity()) {
				this.addActionError("上传失败，该图片大小大于彩信剩余的字节数");
				initDate();
				return "editMsg";
			}
			
			String filename = this.generateFileName(getHouzhui(this.pic1ContentType));
			File picfile = new File(this.getProjectPath() + Constants.MSG_MOBAN_PIC_PATH + filename);
			picfile.createNewFile();
			FileUtils.copyFile(pic1, picfile);
			
			//把数据保存在session
			ManageMsgDetail msgDetail = this.getSessionMsgDetail(this.zhenNumber);
			//不为空则先删除之前的
			if (msgDetail.getPic() != null) {
				//new File(this.getProjectPath() + msgDetail.getPic()).delete(); 不删除
			}
			msgDetail.setPic(Constants.MSG_MOBAN_PIC_PATH + filename);
			msgDetail.setInterval(interval1);
			this.saveMsgDetail(msgDetail);
			this.addActionMessage("彩信图片上传成功");
		} else {
			this.addActionError("请选中你要上传的文件");
		}
		initDate();
		return "editMsg";
	}
	
	public String uploadTxt() throws Exception {
		System.out.println("uploadTxt...........");
		initDate();
		if (txt1 != null) {
			//检查类型
			if (!this.txt1ContentType.equals("text/plain")) {
				this.addActionError("上传失败,彩信文字的格式有误,请重新上传");
				return "editMsg";
			}
			//检查大小
			if (txt1.length() > getRemainCapacity()) {
				this.addActionError("上传失败，该文件大小大于彩信剩余的字节数");
				return "editMsg";
			}
			
			FileCharsetDetector fcd = new FileCharsetDetector();
			String encoding = fcd.guestFileEncoding(txt1);
			String tmpContent = "";
			if (encoding == null) {
				tmpContent = FileUtils.readFileToString(txt1);
			} else {
				tmpContent = FileUtils.readFileToString(txt1, encoding);
			}
			
			//把数据保存在session
			ManageMsgDetail msgDetail = this.getSessionMsgDetail(this.zhenNumber);
			msgDetail.setInterval(interval1);
			msgDetail.setTxt(tmpContent);
			this.saveMsgDetail(msgDetail);
			this.addActionMessage("彩信文字上传成功");
		} else {
			this.addActionError("请选中你要上传的文件");
		}
		return "editMsg";
	}
	
	public String uploadMusic() throws Exception {
		System.out.println("uploadMusic...........");
		initDate();
		if (music1 != null) {
			//检查类型
			if (!this.music1ContentType.equals("audio/mid")) {
				this.addActionError("上传失败,彩信音乐的格式有误,请重新上传");
				return "editMsg";
			}
			//检查大小
			if (music1.length() > getRemainCapacity()) {
				this.addActionError("上传失败，该音乐大小大于彩信剩余的字节数");
				return "editMsg";
			}
			
			String filename = this.generateFileName(getHouzhui(this.music1ContentType));
			File musicfile = new File(this.getProjectPath() + Constants.MSG_MOBAN_MUSIC_PATH + filename);
			musicfile.createNewFile();
			FileUtils.copyFile(music1, musicfile);
			
			//把数据保存在session
			ManageMsgDetail msgDetail = this.getSessionMsgDetail(this.zhenNumber);
			//不为空则先删除之前的
			if (msgDetail.getMusic() != null) {
				//new File(this.getProjectPath() + msgDetail.getMusic()).delete();
			}
			msgDetail.setMusic(Constants.MSG_MOBAN_PIC_PATH + filename);
			msgDetail.setInterval(interval1);
			this.saveMsgDetail(msgDetail);
			this.addActionMessage("彩信音乐上传成功");
		} else {
			this.addActionError("请选中你要上传的文件");
		}
		return "editMsg";
	}
	
	public String saveMoban() throws Exception {
		initDate();
		if (StringUtil.isEmpty(title)) {
			this.addActionError("请输入标题");
		}
		//保存一下当前帧的帧间隔时间
		ManageMsgDetail d = this.getSessionMsgDetail(zhenNumber);
		d.setInterval(interval1);
		
		checkMsg();
		if (this.hasErrors()) {
			return "editMsg";
		}
		
		ManageMsg msg = new ManageMsg(); 
		msg.setTitle(title.trim());
		msg.setAddTime(new Date());
		msg.setLabel(label);
		msg.setBisGroup(bisGroupService.findById(bisGroup));
		msg.setBisType(bisTypeService.findById(bisType));
		List<ManageMsgDetail> details = new ArrayList<ManageMsgDetail>();
		if (msg.getBisType().getEditAble() == msg.EDIT_ENABLE) {
			ManageMsgDetail md = this.getSessionMsgDetail(1);
			md.setId(null);
			md.setZhenNo(1);
			if (md.getInterval() == null) {
				md.setInterval(0);
			}
			md.setManageMsg(msg);
			details.add(md);
			
			//干掉后面的
			for (int i = 1; i < MSG_DETAIL_TOTAL; i++) {
				ManageMsgDetail mm = this.getSessionMsgDetail(i + 1);
				if(!StringUtil.isEmpty(mm.getPic())) {
					new File(this.getProjectPath() + mm.getPic()).delete();
				}
				if(!StringUtil.isEmpty(mm.getMusic())) {
					new File(this.getProjectPath() + mm.getMusic()).delete();
				}
			}
		} else {
			for (int i = 0; i < MSG_DETAIL_TOTAL; i++) {
				ManageMsgDetail md = this.getSessionMsgDetail(i + 1);
				md.setId(null);
				if (md.getInterval() == null) {
					md.setInterval(0);
				}
				md.setZhenNo(i + 1);
				md.setManageMsg(msg);
				if (hasContent(md)) {
					details.add(md);
				}
			}
		}
		msg.setManageMsgDetails(details);
		//删掉老的，直接插入新的 
		manageMsgService.deleteById(this.getSessionMsg().getId());
		manageMsgService.save(msg);
		this.addActionMessage("修改成功");
		clearSessionContent();
		return "list";
	}
	
	private void clearSessionContent() {
		this.curMsgDetail = null;
		this.zhenNumber = 1;
		for (int i = 0; i < MSG_DETAIL_TOTAL; i++) {
			this.removeSession(TMP_MSG_DETAIL_KEY + 1);
		}
		this.removeSession(MSG_KEY);
	}
	
	private void checkMsg() {
		boolean r = false;
		for (int i = 0; i < MSG_DETAIL_TOTAL; i++) {
			ManageMsgDetail d = this.getSessionMsgDetail(i + 1);
			if (hasContent(d)) {
				r = true;
			}
		}
		if (!r) {
			this.addActionError("保存失败，模板的内容为空");
		}
	}
	
	private boolean hasContent(ManageMsgDetail d) {
		if (!StringUtil.isEmpty(d.getPic()) || !StringUtil.isEmpty(d.getMusic()) || !StringUtil.isEmpty(d.getTxt())) {
			return true;
		}
		return false;
	}
	
	private void saveMsgDetail(ManageMsgDetail md) {
		this.setSessionAtrribute(TMP_MSG_DETAIL_KEY + md.getZhenNo(), md);
		this.reComputeCapacity();
		this.curMsgDetail = md;
	}
	
	private ManageMsgDetail getSessionMsgDetail(int zhen) {
		Object msgDetail = this.getSessionAtrribute(TMP_MSG_DETAIL_KEY + zhen);
		if (msgDetail == null) {
			return new ManageMsgDetail();
		} else {
			return (ManageMsgDetail) msgDetail;
		}
	}
	
	private ManageMsg getSessionMsg() {
		return (ManageMsg) this.getSessionAtrribute(MSG_KEY);
	}
	
	/**
	 * 获取当前彩信剩余容量
	 * @return
	 */
	private long getRemainCapacity() {
		return   Constants.MSG_MAX_LENGTH - computeTotalCapacity();
	}
	
	/**
	 * 重新计算短信剩余容量
	 */
	private void reComputeCapacity() {
		this.msgCapacity = computeTotalCapacity();
	}
	
	private long computeTotalCapacity() {
		long cp = 0;
		for (int i = 0; i < MSG_DETAIL_TOTAL; i++) {
			ManageMsgDetail z = this.getSessionMsgDetail(i + 1);
			if (z.getPic() != null) {
				cp += new File( this.getProjectPath() + z.getPic()).length();
			}
			if (z.getMusic() != null) {
				cp += new File(this.getProjectPath() + z.getMusic()).length();
			}
			if (z.getTxt() != null) {
				cp += z.getTxt().getBytes().length;
			}
		}
		return cp;
	}
	 
	public ManageMsgDetail getCurMsgDetail() {
		return curMsgDetail;
	}

	public void setCurMsgDetail(ManageMsgDetail curMsgDetail) {
		this.curMsgDetail = curMsgDetail;
	}

	public BisGroupService getBisGroupService() {
		return bisGroupService;
	}

	public void setBisGroupService(BisGroupService bisGroupService) {
		this.bisGroupService = bisGroupService;
	}

	public BisTypeService getBisTypeService() {
		return bisTypeService;
	}

	public void setBisTypeService(BisTypeService bisTypeService) {
		this.bisTypeService = bisTypeService;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public int getInterval1() {
		return interval1;
	}

	public void setInterval1(int interval1) {
		this.interval1 = interval1;
	}


	public File getPic1() {
		return pic1;
	}

	public void setPic1(File pic1) {
		this.pic1 = pic1;
	}


	public File getMusic1() {
		return music1;
	}

	public void setMusic1(File music1) {
		this.music1 = music1;
	}


	public int getBisType() {
		return bisType;
	}

	public void setBisType(int bisType) {
		this.bisType = bisType;
	}
	
	public int getBisGroup() {
		return bisGroup;
	}

	public void setBisGroup(int bisGroup) {
		this.bisGroup = bisGroup;
	}

	public int getLabel() {
		return label;
	}

	public void setLabel(int label) {
		this.label = label;
	}

	public List<BisType> getAllTypes() {
		return allTypes;
	}

	public void setAllTypes(List<BisType> allTypes) {
		this.allTypes = allTypes;
	}

	public List<BisGroup> getGroups() {
		return groups;
	}

	public void setGroups(List<BisGroup> groups) {
		this.groups = groups;
	}

	public String getTxtedit1() {
		return txtedit1;
	}

	public void setTxtedit1(String txtedit1) {
		this.txtedit1 = txtedit1;
	}

	public List<ManageMsgDetail> getYulanList() {
		return yulanList;
	}

	public void setYulanList(List<ManageMsgDetail> yulanList) {
		this.yulanList = yulanList;
	}

	public File getTxt1() {
		return txt1;
	}

	public void setTxt1(File txt1) {
		this.txt1 = txt1;
	}

	public String getEditTxtContent() {
		return editTxtContent;
	}

	public void setEditTxtContent(String editTxtContent) {
		this.editTxtContent = editTxtContent;
	}

	public int getZhenNumber() {
		return zhenNumber;
	}

	public void setZhenNumber(int zhenNumber) {
		this.zhenNumber = zhenNumber;
	}

	public String getPic1ContentType() {
		return pic1ContentType;
	}

	public void setPic1ContentType(String pic1ContentType) {
		this.pic1ContentType = pic1ContentType;
	}

	public String getMusic1ContentType() {
		return music1ContentType;
	}
	
	public int getOldZhenNo() {
		return oldZhenNo;
	}

	public void setOldZhenNo(int oldZhenNo) {
		this.oldZhenNo = oldZhenNo;
	}

	public void setMusic1ContentType(String music1ContentType) {
		this.music1ContentType = music1ContentType;
	}

	public String getTxt1ContentType() {
		return txt1ContentType;
	}

	public void setTxt1ContentType(String txt1ContentType) {
		this.txt1ContentType = txt1ContentType;
	}
	
	public int getMsgId() {
		return msgId;
	}

	public void setMsgId(int msgId) {
		this.msgId = msgId;
	}

	public long getMsgCapacity() {
		return msgCapacity;
	}

	public void setMsgCapacity(long msgCapacity) {
		this.msgCapacity = msgCapacity;
	}

	private String generateFileName(String houzhui) {
		return System.currentTimeMillis() + "." + houzhui.toLowerCase();
	}

	public ManageMsgService getManageMsgService() {
		return manageMsgService;
	}

	public void setManageMsgService(ManageMsgService manageMsgService) {
		this.manageMsgService = manageMsgService;
	}

	public int getFirst() {
		return first;
	}

	public void setFirst(int first) {
		this.first = first;
	}

	/**
	 * @param fileType struts2文件上传的类型
	 * @return
	 */
	private String getHouzhui(String fileType) {
		if (fileType.equals("image/gif")) {
			return "gif";
		}else if (fileType.equals("image/jpg") || fileType.equals("image/jpeg")) {
			return "jpg";
		} else if (fileType.equals("text/plain")) {
			return "txt";
		} else if (fileType.equals("audio/mid")) {
			return "mid";
		} else if (fileType.startsWith("image")) {
			return "jpg";
		} 
		return null;
	}
}

